package com.cn.hibernate.base.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import com.cn.hibernate.base.IBaseDao;

@SuppressWarnings("unchecked")
public class BaseDao<T, ID extends Serializable> extends HibernateDaoSupport implements IBaseDao<T, ID> {

	protected Class<T> entityClass;

	public BaseDao() {
	}

	protected Class getEntityClass() {
		if (entityClass == null) {
			entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		}
		return entityClass;
	}

	@Override
	public void saveOrUpdate(T t) {
		getHibernateTemplate().saveOrUpdate(t);
	}

	@Override
	public Serializable save(T t) {
		return getHibernateTemplate().save(t);
	}

	@Override
	public void update(T t) {
		getHibernateTemplate().update(t);
	}

	@Override
	public T load(ID id) {
		return (T) getHibernateTemplate().load(getEntityClass(), id);
	}

	@Override
	public T get(ID id) {
		return (T) getHibernateTemplate().get(getEntityClass(), id);
	}

	@Override
	public boolean contains(T t) {
		return getHibernateTemplate().contains(t);
	}

	@Override
	public void delete(T t) {
		getHibernateTemplate().delete(t);
	}

	@Override
	public void delelteAll(Collection<T> entities) {
		getHibernateTemplate().deleteAll(entities);
	}

	@Override
	public List<T> find(String queryString, Object value) {
		return (List<T>) getHibernateTemplate().find(queryString, value);
	}

	@Override
	public List<T> find(String queryString, Object[] values) {
		return (List<T>) getHibernateTemplate().find(queryString, values);
	}

	@Override
	public List<T> find(String queryString) {
		return (List<T>) getHibernateTemplate().find(queryString);
	}

	@Override
	public void refresh(T t) {
		getHibernateTemplate().refresh(t);
	}
	//可以在xml上写  default-autowire="byName"来省去下面的代码
	@Autowired
	public void setHibernateSessionFactory(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	
}
